package com.wechat.controller;

import com.wechat.annotation.GlobalInterceptor;
import com.wechat.entity.constants.Constants;
import com.wechat.entity.dto.GroupInfoDTO;
import com.wechat.entity.dto.TokenUserInfoDto;
import com.wechat.entity.enums.GroupStatusEnum;
import com.wechat.entity.enums.MessageTypeEnum;
import com.wechat.entity.enums.ResponseCodeEnum;
import com.wechat.entity.enums.UserContactStatusEnum;
import com.wechat.entity.po.GroupInfo;
import com.wechat.entity.po.UserContact;
import com.wechat.entity.query.GroupInfoQuery;
import com.wechat.entity.query.UserContactQuery;
import com.wechat.entity.vo.GroupInfoVO;
import com.wechat.entity.vo.ResponseVO;
import com.wechat.exception.BusinessException;
import com.wechat.service.GroupInfoService;
import com.wechat.service.UserContactService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;

/**
 * 群信息相关业务开发
 */
@RestController
@RequestMapping("/group")
public class GroupInfoController extends ABaseController{
    @Autowired
    private GroupInfoService groupInfoService;
    @Autowired
    private UserContactService userContactService;
    /**
     * 创建群---群主创建
     */
    @RequestMapping("/saveGroup")
    @GlobalInterceptor
    public ResponseVO saveGroup(HttpServletRequest request, @RequestBody GroupInfoDTO groupInfoDTO) throws IOException {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);
        //保存群信息
        GroupInfo groupInfo = new GroupInfo();

        BeanUtils.copyProperties(groupInfoDTO, groupInfo);
        groupInfo.setGroupOwnerId(tokenUserInfoDto.getUserId());//设置群主id
        groupInfo.setStatus(Constants.ONE);

        groupInfoService.saveGroup(groupInfo, groupInfoDTO.getAvatarFile(), groupInfoDTO.getAvatarCover());

        return getSuccessResponseVO(null);

    }

    /**
     * 加载群列表
     */
    @RequestMapping("/loadMyGroup")
    @GlobalInterceptor
    public ResponseVO loadGroup(HttpServletRequest request) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        //设置查询条件---根据当前用户ID查询群组
        GroupInfoQuery groupInfoQuery = new GroupInfoQuery();
        groupInfoQuery.setGroupOwnerId(tokenUserInfo.getUserId());
        groupInfoQuery.setOrderBy("create_time desc");
        List<GroupInfo> groupInfoList = groupInfoService.findListByParam(groupInfoQuery);
        return getSuccessResponseVO(groupInfoList);
    }


    /**
     * 获取群组信息
     * @param groupId
     * @return
     */
    @RequestMapping("/getGroupInfo")
    @GlobalInterceptor
    public ResponseVO getGroupInfo(HttpServletRequest request,@NotEmpty String groupId) {
        GroupInfo groupInfo = getInfo(request, groupId);//获取群信息
        //封装查询条件---根据群组id查询
        UserContactQuery userContactQuery = UserContactQuery.builder()
                .contactId(groupId)
                .build();
        Integer countByParam = userContactService.findCountByParam(userContactQuery);
        groupInfo.setMemberCount(countByParam);
        return getSuccessResponseVO(groupInfo);
    }


    /**
     * 获取群组联系人信息
     * @param groupId
     * @return
     */
    @RequestMapping("/getGroupInfo4Chat")
    @GlobalInterceptor
    public ResponseVO getGroupInfo4Chat(HttpServletRequest request,@NotEmpty String groupId) {
        GroupInfo groupInfo = getInfo(request, groupId);//获取群信息

        //封装查询条件
        UserContactQuery userContactQuery = UserContactQuery.builder()
                .contactId(groupId)
                .queryUserInfo(true)//关联查询用户信息
                .status(UserContactStatusEnum.FRIEND.getStatus())
                .build();
        userContactQuery.setOrderBy("create_time asc");
        //获取群成员信息
        List<UserContact> listByParam = userContactService.findListByParam(userContactQuery);

        GroupInfoVO groupInfoVO = new GroupInfoVO();
        groupInfoVO.setGroupInfo(groupInfo);
        groupInfoVO.setUserContactList(listByParam);

        return getSuccessResponseVO(groupInfoVO);
    }

    /**
     * 获取群信息
     * @param request
     * @param groupId
     * @return
     */
    private GroupInfo getInfo(HttpServletRequest request, String groupId) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        String userId = tokenUserInfo.getUserId();
        // 判断用户是否是群成员
        UserContact userContactByUserIdAndContactId = userContactService.getUserContactByUserIdAndContactId(userId, groupId);
        if (userContactByUserIdAndContactId == null || userContactByUserIdAndContactId.getStatus() != UserContactStatusEnum.FRIEND.getStatus()) {
            throw new BusinessException("群聊不存在或您不在群聊内");
        }
        GroupInfo groupInfo = groupInfoService.getGroupInfoByGroupId(groupId);
        if (groupInfo == null || !groupInfo.getStatus().equals(GroupStatusEnum.NORMAL.getStatus())) {
            throw new BusinessException("群聊不存在或已解散");
        }
        return groupInfo;
    }

    /**
     * 添加或移除群成员
     * @param request
     * @param groupId
     * @param selectContacts
     * @param opType
     * @return
     */
    @RequestMapping("/addOrRemoveGroupUser")
    @GlobalInterceptor
    public ResponseVO addOrRemoveGroupUser(HttpServletRequest request,
                                           @NotEmpty String groupId,
                                           @NotEmpty String selectContacts,
                                           @NotNull Integer opType) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        groupInfoService.addOrRemoveGroupUser(tokenUserInfo, groupId, selectContacts, opType);
        return getSuccessResponseVO(null);
    }

    /**
     * 退出群聊
     * @param request
     * @param groupId
     * @return
     */
    @RequestMapping("/leaveGroup")
    @GlobalInterceptor
    public ResponseVO leaveGroup(HttpServletRequest request,
                                           @NotEmpty String groupId) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        groupInfoService.leaveGroup(tokenUserInfo.getUserId(), groupId, MessageTypeEnum.LEAVE_GROUP);
        return getSuccessResponseVO(null);
    }

    /**
     * 解散群聊
     * @param request
     * @param groupId
     * @return
     */
    @RequestMapping("/dissolutionGroup")
    @GlobalInterceptor
    public ResponseVO dissolutionGroup(HttpServletRequest request,
                                 @NotEmpty String groupId) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        groupInfoService.dissolutionGroup(tokenUserInfo.getUserId(), groupId);
        return getSuccessResponseVO(null);
    }
    
}
